import random
import uuid
from datetime import timedelta

from django.db import models
from django.utils import timezone

from apps.PackageManagement.models import Package
from apps.UserManagement.models import User


class Order(models.Model):
    objects = models.Manager()

    ORDER_STATUS_CHOICES = [
        ('pending', '待付款'),
        ('completed', '已支付'),
        ('cancelled', '已取消'),
        ('refunded', '已退款'),
    ]
    PAYMENT_METHOD_CHOICES = [
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
        ('credit_card', '信用卡支付'),
        ('bank_card', '银行卡支付'),
    ]
    order_no = models.CharField(max_length=12, unique=True, verbose_name="订单编号")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders', verbose_name="用户")
    package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='orders', verbose_name="套餐")
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单金额")
    status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='pending', verbose_name="订单状态")
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, null=True, blank=True,
                                      verbose_name="支付方式")
    transaction_id = models.CharField(max_length=64, null=True, blank=True, verbose_name="交易号")
    paid_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间")
    ORDER_TYPE_CHOICES = [
        ('new', '新购'),
        ('renewal', '续费'),
        ('upgrade', '升级'),
    ]
    order_type = models.CharField(max_length=20, choices=ORDER_TYPE_CHOICES, default='new', verbose_name="订单类型")
    create_time = models.DateTimeField(default=timezone.now, help_text='创建时间')
    update_time = models.DateTimeField(auto_now=True, help_text='更新时间')

    class Meta:
        db_table = 'order'

    def save(self, *args, **kwargs):
        if not self.order_no:
            self.order_no = self.generate_unique_order_no()
        super().save(*args, **kwargs)

    def generate_unique_order_no(self):
        while True:
            order_no = ''.join([str(random.randint(0, 9)) for _ in range(12)])
            if not Order.objects.filter(order_no=order_no).exists():
                return order_no


class UserPackage(models.Model):
    """
    用户套餐订阅记录表
    """
    objects = models.Manager()

    STATUS_CHOICES = (
        ('active', '活跃'),
        ('expired', '已过期'),
        ('disabled', '已禁用'),
    )
    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='packages', verbose_name="用户")
    package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='user_packages', verbose_name="套餐")
    order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='user_package', verbose_name="关联订单",
                                 null=True, blank=True)
    cost = models.DecimalField("合计费用", max_digits=10, decimal_places=2)
    subscription_time = models.DateTimeField("订阅时间")
    expiration_time = models.DateTimeField("到期时间")
    status = models.CharField("状态", max_length=10, choices=STATUS_CHOICES, default='active')

    class Meta:
        db_table = 'user_package'
